<template>
  <div class="shippingOrderUpload">
    <van-form @submit="formSubmitted" ref="form">
      <van-field
        v-model="form.orderNo"
        name="orderNo"
        label="发货单号"
        placeholder="发货单号"
        right-icon="scan"
        class="orderNo"
        :rules="[{ required: true, message: '请填写发货单号' }]"
        @click-right-icon="clickScaneCode"
        @blur="orderNoBlur"
      ></van-field>
      <van-field
        name="uploader"
        label="上传文件"
        :rules="[{ validator: uploadValidator, message: '请上传文件' }]"
      >
        <template #input>
          <van-uploader
            v-model="fileList"
            accept="image/*"
            :max-count="30"
            :multiple="true"
            :max-size="1024 * 1024 * 200"
            :before-delete="beforeDelete"
            :disabled="form.orderNo == '' || !canSend"
            @oversize="uploadOversize"
          />
        </template>
      </van-field>
    </van-form>
    <div class="btnCon">
      <van-button
        class="opeBtn"
        type="info"
        round
        :disabled="!canSend"
        @click="submitClick"
        >提交</van-button
      >
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations } from "vuex";
import wx from "weixin-js-sdk";
import { Form, Field, Toast, Dialog, Uploader, Button, Icon } from "vant";
import wxJSFn from "@/js/wxJSFn";

let timeout = null;
export default {
  components: {
    [Form.name]: Form,
    [Field.name]: Field,
    [Uploader.name]: Uploader,
    [Button.name]: Button,
    [Icon.name]: Icon,
  },
  data() {
    return {
      pageReady: false,
      scaneClick: false,
      form: {
        orderNo: "",
        name: [],
      },
      fileList: [],
      canSend: false,
    };
  },
  mounted() {
    this.initAuth();
  },
  methods: {
    ...mapActions({
      getWxWorkJsApiConfig: "sys/getWxWorkJsApiConfig",
      uploadImg: "t100/uploadImg",
      uploadImgApi: "t100/uploadImgApi",
    }),
    uploadValidator(val) {
      if (this.fileList.length < 1) {
        return false;
      }
      return true;
    },
    initAuth() {
      let self = this;
      this.getWxWorkJsApiConfig({
        url: encodeURI(window.location.href.split("#")[0]),
      })
        .then((res) => {
          console.log(res);
          wx.config({
            debug: false,
            beta: true,
            appId: res.appId,
            timestamp: res.timestamp,
            nonceStr: res.nonceStr,
            signature: res.signature,
            jsApiList: [
              "checkJsApi",
              "chooseImage",
              "previewImage",
              "uploadImage",
              "downloadImage",
              "scanQRCode",
              "closeWindow",
            ],
          });
          wx.ready(() => {
            console.log("wxready");
            self.pageReady = true;
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    initForm() {
      this.form.name = [];
      this.form.orderNo = "";
      this.fileList = [];
    },
    orderNoBlur() {
      if (this.form.orderNo) {
        if (timeout) {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            if (this.scaneClick == false) {
              this.getOrderInfo(this.form.orderNo);
            }
          }, 500);
        } else {
          timeout = setTimeout(() => {
            if (this.scaneClick == false) {
              this.getOrderInfo(this.form.orderNo);
            }
          }, 500);
        }
      } else {
        this.initForm();
      }
    },
    clickScaneCode() {
      console.log("clickScaneCode");
      if (this.pageReady) {
        this.scaneClick = true;
        wxJSFn
          .scaneCode()
          .then((res) => {
            console.log(res);
            this.form.orderNo = res;
            this.$nextTick(() => {
              this.getOrderInfo(res);
            });
          })
          .catch((err) => {
            console.log(err);
            this.scaneClick = false;
          });
      }
    },
    getOrderInfo(orderNo) {
      console.log("getOrderInfo", orderNo);
      this.scaneClick = false;
      this.handleT100Api(2)
        .then((res) => {
          console.log(res);
          this.fileList = [];
          this.form.name = [];
          if (res && res.success) {
            this.canSend = true;
            if (res.data) {
              if (res.data.data && Array.isArray(res.data.data)) {
                res.data.data.forEach((e) => {
                  this.fileList.push({
                    url: `${process.env.VUE_APP_T100_API}${process.env.VUE_APP_T100_PIC}/${orderNo}/${e.NAME}`,
                  });
                  // this.form.name.push({
                  //   picname: `/${orderNo}/${e.NAME}`,
                  // });
                });
              }
            }
          } else {
            this.canSend = false;
            Dialog.alert({
              title: "提示",
              message: res.message,
            }).then(() => {
              // on close
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    submitClick() {
      this.$refs.form.submit();
    },
    handleUploadImg() {
      return new Promise((resolve, reject) => {
        let sendData = {
          params: {
            orderNo: this.form.orderNo,
          },
        };
        let fd = new FormData();
        let flag = false;
        console.log(this.fileList);
        this.fileList.forEach((e) => {
          console.log(e);
          if (e.file) {
            fd.append("attach", e.file);
            flag = true;
          }
        });
        sendData.fd = fd;

        if (flag) {
          this.uploadImg(sendData)
            .then((res) => {
              console.log(res);
              if (res && res.errno == 0) {
                if (res.data && res.data.length > 0) {
                  res.data.forEach((e) => {
                    this.form.name.push({
                      picname: `${e}`,
                    });
                  });
                }
                resolve();
              } else {
                reject("上传图片失败");
              }
            })
            .catch((err) => {
              console.log(err);
              reject(err);
            });
        } else {
          resolve();
        }
      });
    },
    handleT100Api(type) {
      return new Promise((resolve, reject) => {
        let sendData = {
          type,
          no: this.form.orderNo,
        };
        if (type == 1) {
          let nameArr = this.form.name.map((e) => {
            return {
              picname: `${process.env.VUE_APP_T100_REALDIR}${process.env.VUE_APP_T100_PIC}${e.picname}`,
            };
          });
          sendData.name = JSON.stringify(nameArr);
        }
        this.uploadImgApi(sendData)
          .then((res) => {
            resolve(res);
          })
          .catch((err) => {
            console.log(err);
            reject(err);
          });
      });
    },
    uploadOversize() {
      Toast("文件大小不能超过200M");
    },
    deleteUpload(file) {
      console.log(file);
      if (file.file) {
        return;
      }
      let arr = [];
      this.form.name.forEach((e) => {
        if (!file.url.includes(e.picname)) {
          arr.push(e);
        }
      });
      this.form.name = arr;
    },
    beforeDelete(e) {
      console.log(e);
      if (e.file) {
        return true;
      } else {
        Dialog.alert({
          title: "提示",
          message: "已上传的文件请到T100中删除",
        }).then(() => {
          // on close
        });
        return false;
      }
    },
    formSubmitted() {
      Toast.loading({
        message: "上传中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      this.handleUploadImg()
        .then(() => {
          return this.handleT100Api(1);
        })
        .then((res) => {
          console.log(res);
          if (res && res.success) {
            Toast.success("操作成功");
            this.getOrderInfo(this.form.orderNo);
          } else {
            Toast.fail(`操作失败:${res.message}`);
            this.getOrderInfo(this.form.orderNo);
          }
        })
        .catch((err) => {
          Toast.fail(err);
          this.getOrderInfo(this.form.orderNo);
        });
    },
  },
};
</script>

<style lang="scss">
.shippingOrderUpload {
  position: relative;
  height: 100vh;
  // padding-bottom: 178px;
  box-sizing: border-box;
  .orderNo {
    .van-field__left-icon .van-icon,
    .van-field__right-icon .van-icon {
      font-size: 80px;
    }
  }
  .btnCon {
    padding: 36px 24px;
    width: 100vw;
    box-sizing: border-box;
    // position: absolute;
    // left: 0;
    // bottom: 0;
  }
  .opeBtn {
    width: 100%;
    font-size: 50px;
    height: 130px;
  }
  @media screen and (min-width: 600px) {
    .opeBtn {
      font-size: 16px; /* px-to-viewport-ignore */
      height: 60px; /* px-to-viewport-ignore */
    }
    .orderNo {
      .van-field__left-icon .van-icon,
      .van-field__right-icon .van-icon {
        font-size: 24px; /* px-to-viewport-ignore */
      }
    }
  }
}
</style>